package cn.stylefeng.mferp.modular.business.controller;

import cn.stylefeng.mferp.core.util.DateUtil;
import cn.stylefeng.mferp.core.util.ReflectUtil;
import cn.stylefeng.mferp.modular.business.constant.Constants;
import cn.stylefeng.mferp.modular.business.model.OffcutLogModel;
import cn.stylefeng.mferp.modular.business.model.Tjlb;
import cn.stylefeng.mferp.modular.business.model.TjlbSjModel;
import cn.stylefeng.mferp.modular.business.service.IEasyExcelService;
import cn.stylefeng.mferp.modular.business.warpper.OffcutLogWarpper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import cn.stylefeng.mferp.core.log.LogObjectHolder;
import cn.stylefeng.mferp.modular.business.model.OffcutLog;
import cn.stylefeng.mferp.modular.business.service.IOffcutLogService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 剩料记录控制器
 *
 * @author fengshuonan
 * @Date 2020-06-09 07:43:57
 */
@Controller
@RequestMapping("/offcutLog")
public class OffcutLogController extends BaseController {

    private String PREFIX = "/business/offcutLog/";

    @Autowired
    private IOffcutLogService offcutLogService;

    @Autowired
    private IEasyExcelService easyExcelService;

    /**
     * 跳转到剩料记录首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "offcutLog.html";
    }

    /**
     * 跳转到添加剩料记录
     */
    @RequestMapping("/offcutLog_add")
    public String offcutLogAdd() {
        return PREFIX + "offcutLog_add.html";
    }

    /**
     * 跳转到修改剩料记录
     */
    @RequestMapping("/offcutLog_update/{offcutLogId}")
    public String offcutLogUpdate(@PathVariable Integer offcutLogId, Model model) {
        OffcutLog offcutLog = offcutLogService.selectById(offcutLogId);
        model.addAttribute("item",offcutLog);
        LogObjectHolder.me().set(offcutLog);
        return PREFIX + "offcutLog_edit.html";
    }

    /**
     * 获取剩料记录列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String carNumber, @RequestParam(required = false) String originNo,
                       @RequestParam(required = false) String currentNo, @RequestParam(required = false) String start,
                       @RequestParam(required = false) String end, @RequestParam(required = false) String offcutType) {
        Wrapper<OffcutLog> wrapper = new EntityWrapper<>();
        if(StringUtils.isNotBlank(carNumber)) {
            wrapper.like("car_number", carNumber);
        }
        if(StringUtils.isNotBlank(originNo)) {
            wrapper.like("origin_no", originNo);
        }
        if(StringUtils.isNotBlank(currentNo)) {
            wrapper.like("current_no", currentNo);
        }
        if(StringUtils.isNotBlank(start)) {
            wrapper.ge("current_production_date", start);
        }
        if(StringUtils.isNotBlank(end)) {
            wrapper.le("current_production_date", end);
        }
        if(StringUtils.isNotBlank(offcutType)) {
            wrapper.eq("offcut_type", offcutType);
        }
        List<OffcutLog> list = offcutLogService.selectList(wrapper);
        return OffcutLogWarpper.wrap(list);
    }

    /**
     * 新增剩料记录
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(OffcutLog offcutLog) {
        if(StringUtils.isBlank(offcutLog.getCarNumber()) || StringUtils.isBlank(offcutLog.getNum()) ||
        StringUtils.isBlank(offcutLog.getCurrentNo()) || StringUtils.isBlank(offcutLog.getOriginNo())) {
            return new ErrorResponseData(Constants.BUSINESS_OFFCUTLOG_INCOMPLETE_DATA);
        }
        Wrapper<OffcutLog> wrapper = new EntityWrapper<>();
        wrapper.eq("origin_no", offcutLog.getOriginNo());
        wrapper.eq("car_number", offcutLog.getCarNumber());
        wrapper.eq("num", offcutLog.getNum());
        wrapper.eq("current_no", offcutLog.getCurrentNo());
        OffcutLog offcutLog1 = offcutLogService.selectOne(wrapper);
        if(offcutLog1 != null) {
            return new ErrorResponseData(Constants.BUSINESS_OFFCUTLOG_EXISTS);
        }
        offcutLogService.insert(offcutLog);
        return SUCCESS_TIP;
    }

    /**
     * 删除剩料记录
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer offcutLogId) {
        offcutLogService.deleteById(offcutLogId);
        return SUCCESS_TIP;
    }

    /**
     * 修改剩料记录
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(OffcutLog offcutLog) {
        offcutLogService.updateById(offcutLog);
        return SUCCESS_TIP;
    }

    /**
     * 剩料记录详情
     */
    @RequestMapping(value = "/detail/{offcutLogId}")
    @ResponseBody
    public Object detail(@PathVariable("offcutLogId") Integer offcutLogId) {
        return offcutLogService.selectById(offcutLogId);
    }

    /**
     * 统计剩料记录
     */
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    @ResponseBody
    public Object count(@RequestParam(required = false) String carNumber, @RequestParam(required = false) String originNo,
                        @RequestParam(required = false) String currentNo, @RequestParam(required = false) String start,
                        @RequestParam(required = false) String end, @RequestParam(required = false) String offcutType) {
        Wrapper<OffcutLog> wrapperM = new EntityWrapper<>();
        if(StringUtils.isNotBlank(offcutType)) {
            wrapperM.eq("offcut_type", offcutType);
        }
        wrapperM.setSqlSelect("sum(num) as num");
        wrapperM.eq("DATE_FORMAT(origin_production_date, '%c')", DateUtil.getCurrDate("M"));
        OffcutLog monthCount = offcutLogService.selectOne(wrapperM);

        Wrapper<OffcutLog> wrapperY = new EntityWrapper<>();
        if(StringUtils.isNotBlank(offcutType)) {
            wrapperY.eq("offcut_type", offcutType);
        }
        wrapperY.setSqlSelect("sum(num) as num");
        wrapperY.eq("DATE_FORMAT(origin_production_date, '%Y')", DateUtil.getCurrDate("yyyy"));
        OffcutLog yearCount = offcutLogService.selectOne(wrapperY);

        Wrapper<OffcutLog> wrapper = new EntityWrapper<>();
        if(StringUtils.isNotBlank(offcutType)) {
            wrapper.eq("offcut_type", offcutType);
        }
        if(StringUtils.isNotBlank(carNumber)) {
            wrapper.like("car_number", carNumber);
        }
        if(StringUtils.isNotBlank(originNo)) {
            wrapper.like("origin_no", originNo);
        }
        if(StringUtils.isNotBlank(currentNo)) {
            wrapper.like("current_no", currentNo);
        }
        if(StringUtils.isNotBlank(start)) {
            wrapper.ge("current_production_date", start);
        }
        if(StringUtils.isNotBlank(end)) {
            wrapper.ge("current_production_date", end);
        }
        wrapperY.setSqlSelect("sum(num) as num");
        OffcutLog count = offcutLogService.selectOne(wrapperY);

        Map<String, Object> map = new HashMap<>();
        if(monthCount != null && StringUtils.isNotBlank(monthCount.getNum())) {
            map.put("monthCount", monthCount.getNum());
        } else {
            map.put("monthCount", "0");
        }
        if(yearCount != null && StringUtils.isNotBlank(yearCount.getNum())) {
            map.put("yearCount", yearCount.getNum());
        } else {
            map.put("yearCount", "0");
        }
        if(count != null && StringUtils.isNotBlank(count.getNum())) {
            map.put("counts", count.getNum());
        } else {
            map.put("counts", "0");
        }
        return new SuccessResponseData(map);
    }

    /**
     * 砂浆文件下载（失败了会返回一个有部分数据的Excel）
     * <p>1. 创建excel对应的实体对象
     * <p>2. 设置返回的 参数
     * <p>3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/download")
    public void downloadSj(HttpServletResponse response,
                           @RequestParam(required = false) String carNumber, @RequestParam(required = false) String originNo,
                           @RequestParam(required = false) String currentNo, @RequestParam(required = false) String start,
                           @RequestParam(required = false) String end, @RequestParam(required = false) String offcutType,
                           @RequestParam(required = false) String excelType) throws IOException {
        Wrapper<OffcutLog> wrapper = new EntityWrapper<>();
        if(StringUtils.isNotBlank(carNumber)) {
            wrapper.like("car_number", carNumber);
        }
        if(StringUtils.isNotBlank(originNo)) {
            wrapper.like("origin_no", originNo);
        }
        if(StringUtils.isNotBlank(currentNo)) {
            wrapper.like("current_no", currentNo);
        }
        if(StringUtils.isNotBlank(start)) {
            wrapper.ge("current_production_date", start);
        }
        if(StringUtils.isNotBlank(end)) {
            wrapper.le("current_production_date", end);
        }
        if(StringUtils.isNotBlank(offcutType)) {
            wrapper.eq("offcut_type", offcutType);
        }
        List<OffcutLog> list = offcutLogService.selectList(wrapper);
        list = OffcutLogWarpper.wrap(list);
        List<OffcutLogModel> offcutLogModels = new ArrayList<>();
        for (OffcutLog log: list) {
            OffcutLogModel offcutLogModel = new OffcutLogModel();
            ReflectUtil.copyValue(log, offcutLogModel);
            offcutLogModels.add(offcutLogModel);
        }
        easyExcelService.download(response, offcutLogModels, OffcutLogModel.class, "剩料记录", excelType);
    }
}
